package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*登录拦截器*/
@Component   //将拦截器放入容器    在配置类中配置拦截器
public class LoginCheckInterceptor implements HandlerInterceptor {

    /*在进入controller之前进行拦截*/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*获取session中的登录信息*/
        Employee employee = (Employee) request.getSession().getAttribute("SESSION_EMPLOYEE");
        if(employee == null){
            System.out.println("用户未登录，非法访问");
            /*写回错误消息
            * 前端进一步做处理
            * */
            response.getWriter().write(new ObjectMapper().writeValueAsString(ResultInfo.error("NOTLOGIN")));
            return false;   //false是禁止通行
        }else {
            //获取到当前用户，保存到threadLocal
            EmployeeHolder.set(employee);
            return true;
        }
    }
    /*请求即将离开服务器*/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //移除掉当前对象保存在threadLocal中的信息
        EmployeeHolder.remove();
    }
}
